package com.lkm.app_ui.help;

import android.hardware.usb.UsbDevice;

import com.lkm.app_ui.AppConst;
import com.lkm.comlib.task2.DefaultTaskExecutor;
import com.lkm.hardware_connect.IHardwareControler;
import com.lkm.usb_com.connect.USBConnectImple;
import com.lkm.usb_com.connect.UsbConnectTask;

public class UsbCDCConnectTask extends UsbConnectTask {

    public UsbCDCConnectTask(USBConnectImple usbConnectImple) {
        super(usbConnectImple, AppConst.getApplication(), new DefaultTaskExecutor(AppConst.getTaskExecutor(),true), AppConst.getTaskManager2());
    }

    @Override
    protected IHardwareControler createUsbHardwareControler(UsbDevice curUsbDevice) {
        CdcAcm serialPort = new CdcAcm(curUsbDevice);
        if (!serialPort.open())
            return null;
        return new UsbSerialDeviceHardwareControler(serialPort);

    }


    private static class UsbSerialDeviceHardwareControler implements IHardwareControler {
        private CdcAcm serialPort;



        @Override
        public int write(byte[] data) {
            int wl = -1;
            try {
                wl = serialPort.write(data);


            } catch (Exception e) {
                e.printStackTrace();
                return -1;
            }

            return wl;
        }



        public int read(byte[] buf, int len) {
            int s = -1;
            try {
                s = serialPort.read(buf, len);
            } catch (Exception e) {
                e.printStackTrace();
                return -1;
            }
            return s;

        }


        public void close() {
            try {
                serialPort.close();
                serialPort = null;
            } catch (Exception e) {
                e.printStackTrace();
            }

        }


        public UsbSerialDeviceHardwareControler(CdcAcm serialPort) {
            this.serialPort = serialPort;
        }

        int writeTimeout = 50;

        public void setWriteTimeout(int writeTimeout) {
            this.writeTimeout = writeTimeout;
        }

        int readTimeout = 50;

        public void setReadTimeout(int readTimeout) {
            this.readTimeout = readTimeout;
        }

        @Override
        public boolean isConnected() {
            return serialPort.isOpened();
        }
    }
}
